<template>
  <div class="customerManagement">
    <MetaSearchForm @on-search="tableSearch">
      <el-form ref="customerManagement_form" :model="searchData" label-width="80px">
        <el-form-item label="客户名称" class="customerManagement_searchFromItem">
          <el-input v-model="searchData.customerName" placeholder="请输入客户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户简称" class="customerManagement_searchFromItem">
          <el-input v-model="searchData.abbreviation" placeholder="请输入客户简称" clearable></el-input>
        </el-form-item>
      </el-form>
    </MetaSearchForm>
    <MetaPageTable
      ref="customerManagementTable"
      class="customerManagement_table"
      table-title="客户列表"
      :is-auto-req="false"
      :tableData="customerData"
      :req-data="searchDataForTable"
      req-method="post"
      :display-item="displayItem"
      :line-btn-group="lineBtnGroup"
      :btn-group="btnGroup"
      @lineBtnClick="tableInlineBtnClick"
      @btnClick="tableBtnClick"
    />
    <el-dialog
      v-if="customerEditDialogFlag"
      :title="itemEditData.id && itemEditData.id !== '' ? '编辑客户' : '新建客户'"
      :visible.sync="customerEditDialogFlag"
      width="60%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="customerInfo_form" :model="itemEditData" label-width="110px" :rules="customerInfoRules">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="itemEditData.customerName" placeholder="请输入客户名称"></el-input>
        </el-form-item>
        <el-form-item label="客户简称">
          <el-input v-model="itemEditData.abbreviation" placeholder="请输入客户简称"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人">
              <el-input v-model="itemEditData.contactName" placeholder="请输入联系人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="itemEditData.phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="省">
              <el-select v-model="itemEditData.province" placeholder="请选择省" @change="provinceHandleChange">
                <el-option
                  v-for="item in provinceList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="市">
              <el-select v-model="itemEditData.city" placeholder="请选择市" @change="cityHandleChange">
                <el-option
                  v-for="item in cityList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区">
              <el-select v-model="itemEditData.area" placeholder="请选择区">
                <el-option
                  v-for="item in areaList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详细地址">
          <el-input v-model="itemEditData.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="itemEditData.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialogFooter">
        <el-button size="mini" @click="newDialogClose()">取消</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="newDialogSubmit()"
        >保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import deepClone from '../utils/deepClone'
import MetaPageTable from '../components/MetaPageTable'
import MetaSearchForm from '../components/MetaSearchForm'
import { isMobilePhone } from '../utils/validate'
export default {
  name: 'customerManagement',
  components: {
    MetaPageTable,
    MetaSearchForm
  },
  data () {
    let checkName = (rule, value, callback) => {
      if (value.trim() === '') {
        return callback(new Error('请输入客户名称'))
      }else{
        return callback()
      }
    }
    let checkPhone = (rule, value, callback) => {
      if (value !== '' && !isMobilePhone(value)) {
        callback(new Error('请输入正确联系电话'));
      }
      callback();
    }
    return {
      customerEditDialogFlag: false,
      customerData: {},
      searchData : {
        customerName: '',
        abbreviation: ''
      },
      searchDataForTable: {},
      itemEditData: {
        customerName: '',
        abbreviation: '',
        contactName: '',
        province: '',
        city: '',
        area: '',
        phone: '',
        address: '',
        remark: ''
      },
      displayItem: [
        {
          label: '客户名称',
          prop: 'customerName'
        },{
          label: '客户简称',
          prop: 'abbreviation'
        },{
          label: '联系人',
          prop: 'contactName'
        },{
          label: '联系电话',
          prop: 'phone'
        },{
          label: '客户地址',
          prop: 'addr'
        },{
          label: '备注',
          prop: 'remark'
        }
      ],
      btnGroup: [{
        id: 'new',
        title: '新建'
      }],
      lineBtnGroup: [
        {
          id: 'edit',
          title: '编辑',
        },
        {
          id: 'delete',
          title: '删除',
        }
      ],
      customerInfoRules: {
        customerName: [
          { required: true, validator: checkName, trigger: 'blur' },
        ],
        phone: [
          { required: false, validator: checkPhone, trigger: 'blur' },
        ]
      },
      provinceList: [],
      cityList: [],
      areaList: []
    }
  },
  mounted() {
    this.initProvinceList()
    this.initCustomerData(true)
  },
  methods: {
    initCustomerData(reflash) {
      let sData = {}
      sData = this.searchDataForTable
      sData.page = 1
      sData.limit = 99999999
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + 'admin/customer',
        method: "post",
        data: sData
      }).then(res => {
        if (res.data.code === 200) {
          this.customerData = res.data.result
          if(this.customerData.content) {
            for(let i in this.customerData.content) {
              let addr = ''
              for(let j in this.customerData.content[i].areaCodes) {
                addr += this.customerData.content[i].areaCodes[j].name
              }
              if(this.customerData.content[i].address && this.customerData.content[i].address !== '') {
                addr += this.customerData.content[i].address
              }
              this.customerData.content[i].addr = addr
            }
          }
          this.$nextTick(() => {
            this.$refs.customerManagementTable.formDataInit(reflash)
          })
        }else {
          this.$notify.error({
            title: '错误',
            message: res.data.message
          });
        }
      })

    },
    initProvinceList() {
      this.initPCAList(0, 'province')
    },
    tableBtnClick(item) {
      if (item.button === 'new') {
        this.itemEditData = {
          id: '',
          customerName: '',
          abbreviation: '',
          contactName: '',
          province: '',
          city: '',
          area: '',
          phone: '',
          address: ''
        }
        this.customerEditDialogFlag = true
      }
    },
    tableInlineBtnClick(item) {
      if (item.button === 'edit') {
        // 省市区
        this.itemEditData = {
          id: item.rows.id,
          customerName: item.rows.customerName,
          abbreviation: item.rows.abbreviation,
          contactName: item.rows.contactName,
          province: item.rows.province ? parseInt(item.rows.province) : '',
          city: item.rows.city ? parseInt(item.rows.city) : '',
          area: item.rows.areaid ? parseInt(item.rows.areaid) : '',
          phone: item.rows.phone ? item.rows.phone : '',
          address: item.rows.address ? item.rows.address : '',
          remark: item.rows.remark ? item.rows.remark : ''
        }
        this.cityList = []
        this.areaList = []
        this.initPCAList(this.itemEditData.province, 'city', () => {
          this.initPCAList(this.itemEditData.city, 'area')
        })
        this.customerEditDialogFlag = true
      }else if(item.button === 'delete') {
        this.$confirm('确认删除当前客户？', '确认删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + 'admin/customer/delete',
            method: "post",
            data: {
              id: item.rows.id
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.initCustomerData(true)
            }else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              });
            }
          })

        })

      }
    },
    newDialogClose() {
      this.itemEditData = {
        id: '',
        customerName: '',
        abbreviation: '',
        contactName: '',
        province: '',
        city: '',
        area: '',
        phone: '',
        address: '',
        remark: ''
      }
      this.customerEditDialogFlag = false
    },
    newDialogSubmit() {
      this.$refs['customerInfo_form'].validate((valid) => {
        if (valid) {
          let params = {}
          if(this.itemEditData.id && this.itemEditData.id !== '') {
            params.id = this.itemEditData.id
          }
          params.customerName = this.itemEditData.customerName.trim()
          params.abbreviation = this.itemEditData.abbreviation.trim()
          params.contactName = this.itemEditData.contactName
          params.phone = this.itemEditData.phone
          params.province = this.itemEditData.province
          params.city = this.itemEditData.city
          params.areaid = this.itemEditData.area
          params.address = this.itemEditData.address
          params.remark = this.itemEditData.remark
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "admin/customer/edit",
            method: "post",
            data: params
          }).then(res => {
            if (res.data.code === 200) {
              this.initCustomerData(false)
              this.newDialogClose()
            }else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              });
            }
          })
        } else {
          return false;
        }
      });
    },
    tableSearch() {
      let param = {}
      for(let key in this.searchData ) {
        if(key === 'dateBetween') {
          param.datestart = this.searchData[key] && this.searchData[key].length > 0 ? this.searchData[key][0] + ' 00:00:00' : ''
          param.dateend =  this.searchData[key] && this.searchData[key].length > 0 ? this.searchData[key][1] + ' 23:59:59' : ''
        }else {
          param[key] = this.searchData[key]
        }
      }
      this.searchDataForTable = param

      this.initCustomerData(true)
    },
    provinceHandleChange(id) {
      this.cityList = []
      this.areaList = []
      this.itemEditData.city = ''
      this.itemEditData.area = ''
      this.initPCAList(id, 'city')
    },
    cityHandleChange(id) {
      this.areaList = []
      this.itemEditData.area = ''
      this.initPCAList(id, 'area')
    },
    initPCAList(id, type, callback) {
      if(id === '') {
        return
      }
      let data = {}
      if(type === 'province') {
        data.level = 1
      }else if (type === 'city') {
        data.level = 2
      }else if (type === 'area') {
        data.level = 3
      }
      data.parentid = id
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/company/area",
        method: "post",
        data: data
      }).then(res => {
        if(type === 'province') {
          this.provinceList = res.data.result
        }else if (type === 'city') {
          this.cityList = res.data.result
        }else if (type === 'area') {
          this.areaList = res.data.result
        }
        if(callback && typeof(callback) === 'function') {
          callback()
        }
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.customerManagement{
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: scroll;
  .customerManagement_searchFromItem {
    float: left;
  }
  .customerManagement_table {
    width: 100%;
    overflow-y: unset;
  }
  .customerInfo_provinceCityCascader {
    width: 100%;
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
}
</style>
